import React, { FC, memo, useCallback, useState } from "react"
import { Divider } from "antd"

interface onClickProps {
  onClick: () => void
}

const ChildComponent1: FC<onClickProps> = memo(({ onClick }) => {
  console.log("Child 1 Rendered")
  return (
    <>
      <h2>Child Component without useCallback reRender {performance.now()}</h2>
      <button onClick={onClick}>点击我</button>
    </>
  )
})

const ChildComponent2: FC<onClickProps> = memo(({ onClick }) => {
  console.log("Child 2 Rendered")
  return (
    <>
      <h2>
        Child Component with useCallback reRender only when parent count change{" "}
        {performance.now()}
      </h2>
      <button onClick={onClick}>点击我</button>
    </>
  )
})

const UseCallbackPage: FC = () => {
  const [count, setCount] = useState(0)
  const [count2, setCount2] = useState(0)
  const handleClick = () => {
    console.log("handleClick triggered")
  }

  const handleClick2 = useCallback(() => {
    console.log("handleClick with useCallback triggered")
  }, [count])

  return (
    <>
      <h1>use Callback learning</h1>
      <h2>useCallback函数的依赖项 {count}</h2>
      <h2>useCallback函数的依赖项 {count2}</h2>
      <button onClick={() => setCount2((c) => c + 1)}>
        点击我不改变useCallback函数的依赖项
      </button>
      <button onClick={() => setCount((c) => c + 1)}>
        点击我改变useCallback函数的依赖项 count
      </button>
      <Divider />
      <ChildComponent1 onClick={handleClick} />
      <Divider />
      <ChildComponent2 onClick={handleClick2} />
    </>
  )
}

export default UseCallbackPage
